﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;
using Domain.Models;
using UI.Presenters;
using UI.Views;

namespace Tester
{
    /// <summary>
    /// Логика взаимодействия для RedactorWindow.xaml
    /// </summary>
    public partial class RedactorWindow : Window, IRedactorView
    {
        private readonly RedactorPresenter presenter;

        public RedactorWindow()
        {
            InitializeComponent();
            presenter = new RedactorPresenter(this);
        }

        #region IRedactorView Members

        public RedactorPresenter Presenter
        {
            get { return presenter; }
        }

        public void AddQuestion(string questionText, long questionId, IEnumerable<Answer> answers, Answer trueAnswer)
        {
            VariantGrid.RowDefinitions.Add(new RowDefinition());

            StackPanel questionStackPanel = AddQuestionTextAndDeleteButton(questionText, questionId, answers, trueAnswer);
            VariantGrid.Children.Add(questionStackPanel);

            StackPanel answersStackPanel = AddAnswersAndDeleteAnswerButtons(questionId, answers);
            VariantGrid.Children.Add(answersStackPanel);

            var separatorRectangle = new Rectangle
                                         {
                                             Height = 2,
                                             VerticalAlignment = VerticalAlignment.Bottom,
                                             StrokeThickness = 1,
                                             Stroke = Brushes.DarkSeaGreen
                                         };
            separatorRectangle.SetValue(Grid.ColumnSpanProperty, 2);
            separatorRectangle.SetValue(Grid.RowProperty, VariantGrid.RowDefinitions.Count - 1);
            VariantGrid.Children.Add(separatorRectangle);
        }

        public void Clear()
        {
            VariantGrid.Children.Clear();
        }

        public void AddAddQuestionButton()
        {
            var addNewQuestionButton = new Button
                                           {
                                               Content = "Добавить вопрос",
                                               Padding = new Thickness(2),
                                               Margin = new Thickness(2)
                                           };
            addNewQuestionButton.Click += AddNewQuestionButton_Click;
            MainStackPanel.Children.Add(addNewQuestionButton);
        }

        public void AddVariantToComboBox(int number)
        {
            VariantComboBox.Items.Add(number);
        }

        public void DeleteVariantFromCombobox(int number)
        {
            VariantComboBox.Items.Remove(number);
        }

        public void RefreshComboBox(long questionId, IEnumerable<Answer> answers, Answer trueAnswer)
        {
            foreach (object child in VariantGrid.Children)
            {
                if (child is StackPanel == false) continue;

                foreach (object stackChild in ((StackPanel) child).Children)
                {
                    if (stackChild is ComboBox == false) continue;

                    var comboBox = stackChild as ComboBox;

                    if ((long) comboBox.Tag != questionId) continue;

                    comboBox.ItemsSource = answers;
                    comboBox.SelectedItem = null;
                    comboBox.SelectedItem = trueAnswer;
                    comboBox.Items.Refresh();
                }
            }
        }

        public void AddSubjectToComboBox(string subjectName)
        {
            newSubjectNameTextBox.Text = "";
            SubjectComboBox.Items.Add(subjectName);
        }

        public int GetCurrentVariantIndex()
        {
            return int.Parse(VariantComboBox.SelectedItem.ToString()) - 1;
        }

        public string GetCurrentSubjectName()
        {
            return SubjectComboBox.SelectedItem.ToString();
        }

        #endregion

        private StackPanel AddAnswersAndDeleteAnswerButtons(long questionId, IEnumerable<Answer> answers)
        {
            var answersStackPanel = new StackPanel
                                        {Margin = new Thickness(5), VerticalAlignment = VerticalAlignment.Center};
            answersStackPanel.SetValue(Grid.RowProperty, VariantGrid.RowDefinitions.Count - 1);
            answersStackPanel.SetValue(Grid.ColumnProperty, 1);

            foreach (Answer answer in answers)
            {
                var singleAnswerStackPanel = new StackPanel {Orientation = Orientation.Horizontal};
                var deleteAnswerButton = new Button
                                             {Tag = answer.Id, Content = "Удалить ответ", Padding = new Thickness(2)};
                deleteAnswerButton.Click += DeleteAnswerButton_Click;

                var answerTextBox = new TextBox
                                        {Text = answer.Text, Margin = new Thickness(2), Width = 100, Tag = answer.Id};
                answerTextBox.LostFocus += AnswerTextBoxEdited;

                singleAnswerStackPanel.Children.Add(answerTextBox);
                singleAnswerStackPanel.Children.Add(deleteAnswerButton);

                answersStackPanel.Children.Add(singleAnswerStackPanel);
            }

            var addAnswerButton = new Button {Tag = questionId, Content = "Добавить ответ", Padding = new Thickness(2)};
            addAnswerButton.Click += addAnswerButton_Click;

            answersStackPanel.Children.Add(addAnswerButton);
            return answersStackPanel;
        }

        private StackPanel AddQuestionTextAndDeleteButton(string questionText, long questionId,
                                                          IEnumerable<Answer> answers, Answer trueAnswer)
        {
            var questionStackPanel = new StackPanel
                                         {Margin = new Thickness(5), VerticalAlignment = VerticalAlignment.Center};
            questionStackPanel.SetValue(Grid.RowProperty, VariantGrid.RowDefinitions.Count - 1);

            var questionTextBox = new TextBox
                                      {Tag = questionId, Text = questionText, Margin = new Thickness(2), Width = 150};
            questionTextBox.LostFocus += QuestionTextEdited;
            questionStackPanel.Children.Add(questionTextBox);

            questionStackPanel.Children.Add(new Label {Content = "Правильный ответ"});

            var trueAnswerComboBox = new ComboBox
                                         {
                                             Margin = new Thickness(2),
                                             ItemsSource = answers,
                                             DisplayMemberPath = "Text",
                                             SelectedValuePath = "Id",
                                             Tag = questionId,
                                             SelectedItem = trueAnswer,
                                             Width = 150
                                         };
            trueAnswerComboBox.SelectionChanged += TrueAnswerChanged;
            questionStackPanel.Children.Add(trueAnswerComboBox);

            var deleteQuestionButton = new Button
                                           {Tag = questionId, Content = "Удалить вопрос", Padding = new Thickness(2)};
            deleteQuestionButton.Click += DeleteQuestionButton_Click;
            questionStackPanel.Children.Add(deleteQuestionButton);
            return questionStackPanel;
        }

        private void TrueAnswerChanged(object sender, SelectionChangedEventArgs e)
        {
            object value = ((ComboBox) e.Source).SelectedValue;
            if (value == null)
                return;
            presenter.ChangeTrueAnswer((long) value);
        }

        private void AnswerTextBoxEdited(object sender, RoutedEventArgs e)
        {
            var answerId = (long) ((TextBox) e.Source).Tag;
            string newAnswerText = ((TextBox) e.Source).Text;

            presenter.EditAnswer(answerId, newAnswerText);
        }

        private void QuestionTextEdited(object sender, RoutedEventArgs e)
        {
            var questionId = (long) ((TextBox) e.Source).Tag;
            string newQuestionText = ((TextBox) e.Source).Text;

            presenter.EditQuestion(questionId, newQuestionText);
        }

        private void AddNewQuestionButton_Click(object sender, RoutedEventArgs e)
        {
            presenter.AddQuestion();
        }

        public void DeleteQuestionButton_Click(object sender, RoutedEventArgs e)
        {
            presenter.DeleteQuestion((long) ((Button) e.Source).Tag);
        }

        private void DeleteAnswerButton_Click(object sender, RoutedEventArgs e)
        {
            presenter.DeleteAnswer((long) ((Button) e.Source).Tag);
        }

        private void addAnswerButton_Click(object sender, RoutedEventArgs e)
        {
            presenter.AddAnswer((long) ((Button) e.Source).Tag);
        }

        private void CreateNewVariant_Click(object sender, RoutedEventArgs e)
        {
            var ints = new List<int>();

            foreach (object item in VariantComboBox.Items)
                ints.Add(int.Parse(item.ToString()));

            if (ints.Count == 0)
                presenter.CreateNewVariant(1);
            else
            {
                ints.Sort();
                presenter.CreateNewVariant(ints[ints.Count - 1] + 1);
            }
        }

        private void DeleteVariant_OnClick(object sender, RoutedEventArgs e)
        {
            MessageBoxResult confirmResult =
                MessageBox.Show(
                    string.Format("Вы дейстdительно хотите удалить вариант {0}", VariantComboBox.SelectedItem),
                    "Подтверждение", MessageBoxButton.YesNo, MessageBoxImage.Exclamation);

            if (confirmResult == MessageBoxResult.Yes)
                presenter.DeleteVariant();
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            presenter.SaveSubject(GetCurrentSubjectName());
//            presenter.SaveVariant(int.Parse(VariantComboBox.Text));
        }

        private void VariantComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (VariantComboBox.SelectedItem != null)
            {
                var variantNumber = int.Parse(VariantComboBox.SelectedItem.ToString());

                if (variantNumber >= 0)
                {
                    string variantSwitchedFrom = "";

                    try
                    {
                        variantSwitchedFrom = e.RemovedItems[0].ToString(); // при ошибке variantSwitchedFrom остается == ""
                    }
                    catch (Exception) { }

                    if (variantSwitchedFrom != "")
                    {
                        presenter.SaveVariant(int.Parse(variantSwitchedFrom));
                    }

                    var variantIndex = variantNumber - 1;

                    presenter.LoadVariant(variantIndex);
                }
            }
        }

        private void SubjectComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var newSubjectName = (string) SubjectComboBox.SelectedItem;
            if (string.IsNullOrEmpty(newSubjectName) == false)
            {
                string subjectSwitchedFrom = "";
                try
                {
                    subjectSwitchedFrom = e.RemovedItems[0].ToString();
                }
                catch(Exception ex){}

                if (subjectSwitchedFrom != "")
                {
                    presenter.SaveSubject(subjectSwitchedFrom);
                }
                
                presenter.LoadSubject(newSubjectName);
            }
        }

        private void CreateSubjectButton_Click(object sender, RoutedEventArgs e)
        {
            presenter.CreateSubject(newSubjectNameTextBox.Text);
        }

        private void DeleteSubjectButton_OnClick(object sender, RoutedEventArgs e)
        {
            presenter.DeleteSubject(SubjectComboBox.SelectedItem.ToString());
            
            SubjectComboBox.Items.Remove(SubjectComboBox.SelectedItem);
        }
    }
}